

package cn.shengchao.examstar.pay.utils.pay;

import cn.shengchao.base.utils.SpringContextHolder;
import cn.shengchao.examstar.pay.utils.config.WxUtil;
import cn.shengchao.examstar.pay.utils.config.WxXcxPayConfig;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.service.WxPayService;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class WechatXcxPay extends WechatPayAbstract {

    @Override
    public UIPayResponse<WxPayMpOrderResult> createPayOrder(PayContext payContext) throws Exception {
        WxPayService wxPayService = WxUtil.WX_XCX_PAY_SERVICE;
        if (wxPayService != null) {
            WxPayUnifiedOrderRequest request = WxPayUnifiedOrderRequest.newBuilder()
                    .body(payContext.getBody())
                    .outTradeNo(payContext.getOrderId())
                    .totalFee(payContext.getPrice())
                    .spbillCreateIp(payContext.getIp())
                    .notifyUrl(Objects.requireNonNull(SpringContextHolder.getBean(WxXcxPayConfig.class)).getNotifyUrl() + payContext.getOrderId())
                    .openid(payContext.getOpenId())
                    .tradeType("JSAPI")
                    .build();
            request.setSignType("MD5");
            WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(request);
            return new UIPayResponse<>(wxPayMpOrderResult, payContext.getOrderId());
        } else {
            log.error("支付异常：{}", payContext.getOrderId());
            throw new IllegalAccessException("支付失败！");
        }
    }

    @Override
    public long queryPayOrder(String orderId) throws Exception {
        try {
            WxPayService wx = WxUtil.WX_XCX_PAY_SERVICE;
            WxPayOrderQueryResult wxOrder = Objects.requireNonNull(wx).queryOrder("", orderId);
            if (!"SUCCESS".equals(wxOrder.getResultCode())) {
                log.error("【微信统一支付】发起支付, resultCode != SUCCESS, err_code = {}, err_code_des={}", wxOrder
                        .getErrCode(), wxOrder.getErrCodeDes());
                return 0;
            }
            if (!"SUCCESS".equals(wxOrder.getReturnCode())) {
                log.error("【微信统一支付】查询支付, returnCode != SUCCESS, returnMsg ={} ", wxOrder.getReturnMsg());
                return 0;
            }
            if (!"SUCCESS".equals(wxOrder.getTradeState())) {
                log.error("【微信统一支付】发起支付, resultCode != SUCCESS, err_code = {}, err_code_des={}", wxOrder
                        .getErrCode(), wxOrder.getErrCodeDes());
                return 0;
            }
            return wxOrder.getTotalFee();
        } catch (Exception e) {
            log.error("【微信统一支付】查询支付异常", e);
            return 0;
        }
    }
}
